package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"user-login-reg/model/cache"
	"user-login-reg/model/mysql"
	"user-login-reg/pkg"

	"user-login-reg/regrpc/internal/svc"
	"user-login-reg/regrpc/regrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户登录
func (l *LoginLogic) Login(in *regrpc.LoginRequest) (*regrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if result != in.Captcha {
		return nil, errors.New("图形验证码错误")
	}
	i, _ := cache.Rdb.Get(l.ctx, "sendsms"+in.Account).Result()

	if i != in.Sendsms {
		return nil, errors.New("短信验证码错误")
	}

	creatuser := mysql.User{
		Model:    gorm.Model{},
		Account:  in.Account,
		Password: pkg.Md5(in.Password),
	}
	err := creatuser.FindOrCreat(mysql.DB, in.Account)
	if err != nil {
		return nil, err
	}

	if creatuser.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码错误")
	}

	return &regrpc.LoginResponse{
		UserId: int64(creatuser.ID),
	}, nil
}
